package yrl.threads.account;

public class Account {
	private double balance = 1000;

	/**
	 * @return the balance
	 */
	public double getBalance() {
		return balance;
	}

	/**
	 * @param balance the balance to set
	 */
	public void setBalance(double balance) {
		this.balance = balance;
	}

	public synchronized void drawMoney(double amount) {
		System.out.println(Thread.currentThread().getName() + "执行取钱操作：");
		double newBalance = this.balance - amount;
		try {
			Thread.sleep(10);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		if (newBalance >= 0) {
			this.balance = newBalance;
			System.out.println("取钱" + amount + "成功，账户余额：" + this.balance);
		} else {
			System.out.println("取钱" + amount + "失败，账户余额不足");
		}
	}

	public synchronized void saveMoney(double amount) {
		System.out.println(Thread.currentThread().getName() + "执行存钱操作：");
		double oldBalance = this.balance;
		try {
			Thread.sleep(10);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		double newBalance = oldBalance + amount;
		this.balance = newBalance;
		System.out.println("存钱" + amount + "成功，账户余额：" + this.balance);
	}

	public synchronized static void test() {//synchronized 修饰静态方法
		System.out.println(Thread.currentThread().getName() + "start......");
//		try {
//			Thread.sleep(10);
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		}
		System.out.println(Thread.currentThread().getName() + "end......");
	}

	public static void test1() {//synchronized 静态方法-锁住当前类
		synchronized (Account.class) {
			System.out.println(Thread.currentThread().getName() + "start......");
//			try {
//				Thread.sleep(10);
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
			System.out.println(Thread.currentThread().getName() + "end......");
		}

	}
}
